//
//  FlickrPhotosViewController.m
//  FlickrSearch-UICollectionView
//
//  Created by cygarm on 15/10/4.
//  Copyright © 2015年 cygarm. All rights reserved.
//

#import "FlickrPhotosViewController.h"
#import "FlickrSearcher.h"
#import "FlickrPhotoCell.h"
#import "FlickrPhotoHeaderView.h"

static NSString * const reuseIdentifier = @"FlickrCell";

@interface FlickrPhotosViewController () <UITextFieldDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property(nonatomic, strong) NSMutableArray<FlickrSearchResults *> *searches;
@property(nonatomic, strong) Flickr *flickr;
@property(nonatomic, strong) NSIndexPath *largePhotoIndexPath;
@property(nonatomic, strong) NSMutableArray<FlickrPhoto *> *selectedPhotos;
@property(nonatomic, strong) UILabel *shareTextLabel;
@property(nonatomic) BOOL sharing;

@end

@implementation FlickrPhotosViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	
	// Uncomment the following line to preserve selection between presentations
	// self.clearsSelectionOnViewWillAppear = NO;
	
	// Register cell classes
	// !!!: delete "registerClass:forCellWithReuseIdentifier:"
	// 详见  http://stackoverflow.com/questions/19523507/uiimageview-in-custom-uicollectionviewcell-returning-nil-all-the-time
	// !!!: UICollectionViewCell -> FlickrPhotoCell
	// 教程里面用的都是UICollectionViewCell,会导致"[UICollectionViewCell imageView]: unrecognized selector"
//	[self.collectionView registerClass:[FlickrPhotoCell class] forCellWithReuseIdentifier:reuseIdentifier];
	
	// Do any additional setup after loading the view.
#pragma mark - Global Variable Init	
	self.searches = [@[] mutableCopy];
	self.flickr = [[Flickr alloc] init];	
	self.shareTextLabel = [[UILabel alloc] init];
	self.selectedPhotos = [NSMutableArray array];
	
	
	[self addObserver:self forKeyPath:@"largePhotoIndexPath" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:NULL];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Multiple Selection Handle

- (IBAction)share:(id)sender {
	NSLog(@"IBAction share");
	if (self.searches.count == 0) {
		return;
	}
	if (self.selectedPhotos.count != 0) {
		NSMutableArray<UIImage *> *imageArray = [NSMutableArray array];
		for (FlickrPhoto *photo in self.selectedPhotos) {
			[imageArray addObject:photo.thumbnail];
		}
		UIActivityViewController *shareScreen = [[UIActivityViewController alloc] initWithActivityItems:imageArray applicationActivities:nil];
//		UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:shareScreen];
//		[popover presentPopoverFromBarButtonItem:self.navigationItem.rightBarButtonItems.firstObject permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		shareScreen.modalPresentationStyle = UIModalPresentationPopover;
		shareScreen.popoverPresentationController.barButtonItem = self.navigationItem.rightBarButtonItems.firstObject;
//		shareScreen.popoverPresentationController.sourceView = self.view;
		[self presentViewController:shareScreen animated:YES completion:nil];
	}
	
	self.sharing = !self.sharing;
}

- (void)updateSharedPhotoCount
{
	self.shareTextLabel.text = [NSString stringWithFormat:@"%lu photos selected", (unsigned long)self.selectedPhotos.count];
	[self.shareTextLabel sizeToFit];
}

- (void)setSharing:(BOOL)sharing
{
	NSLog(@"setSharing:%d->%d", _sharing, sharing);
	_sharing = sharing;
	
	
	self.collectionView.allowsMultipleSelection = sharing;
	// 'nil' 取消当前所有已选items
	[self.collectionView selectItemAtIndexPath:nil animated:YES scrollPosition:UICollectionViewScrollPositionNone];
//	for (NSIndexPath *indexPath in [self.collectionView indexPathsForSelectedItems]) {
////		UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
////		cell.selected = NO;
//		[self.collectionView deselectItemAtIndexPath:indexPath animated:YES];
//	}
	
	[self.selectedPhotos removeAllObjects];
	if (_sharing && self.largePhotoIndexPath != nil) {
		self.largePhotoIndexPath = nil;
	}
	
	UIBarButtonItem *shareButton = self.navigationItem.rightBarButtonItems.firstObject;
	if (_sharing) {
		[self updateSharedPhotoCount];
		UIBarButtonItem *sharingDetailItem = [[UIBarButtonItem alloc] initWithCustomView:self.shareTextLabel];
		[self.navigationItem setRightBarButtonItems:@[shareButton, sharingDetailItem] animated:YES];
	} else {
		[self.navigationItem setRightBarButtonItems:@[shareButton] animated:YES];
	}
}

#pragma mark - KVO

- (void)largePhotoIndexPathDidSet:(NSIndexPath *)newValue oldValue:(NSIndexPath *)oldValue
{		
	NSMutableArray<NSIndexPath *> *indexPaths = [NSMutableArray array];
	NSLog(@"newValue=%@, oldValue=%@", newValue, oldValue);
	if (![newValue isEqual:[NSNull null]]) {
		[indexPaths addObject:newValue];
	}
	if (![oldValue isEqual:[NSNull null]]) {

		[indexPaths addObject:oldValue];
	}
	
	
	[self.collectionView performBatchUpdates:^{
		[self.collectionView reloadItemsAtIndexPaths:indexPaths];
	} completion:^(BOOL finished) {
		if (self.largePhotoIndexPath != nil) {
			[self.collectionView scrollToItemAtIndexPath:self.largePhotoIndexPath 
																	atScrollPosition:UICollectionViewScrollPositionCenteredVertically 
																					animated:YES];
		}
	}];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
	if ([keyPath isEqual:@"largePhotoIndexPath"]) {
		[self largePhotoIndexPathDidSet:[change objectForKey:NSKeyValueChangeNewKey] 
													 oldValue:[change objectForKey:NSKeyValueChangeOldKey]];
	}
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>


- (FlickrPhoto *)photoForIndexPath:(NSIndexPath *)indexPath
{	
	return self.searches[indexPath.section].searchResults[indexPath.row];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
  return self.searches.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.searches[section].searchResults.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	FlickrPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
	
	NSLog(@"cellForItemAtIndexPath:%@", indexPath);
	
	FlickrPhoto *flickrPhoto = [self photoForIndexPath:indexPath];
	
	[cell.activityIndicator stopAnimating];
	
	if (indexPath != self.largePhotoIndexPath) {
		cell.imageView.image = flickrPhoto.thumbnail;
		return cell;
	}
	
	if (flickrPhoto.largeImage != nil) {
		cell.imageView.image = flickrPhoto.largeImage;
		return cell;
	}
	
	cell.imageView.image = flickrPhoto.thumbnail;
	[cell.activityIndicator startAnimating];		
	NSLog(@"[cell.activityIndicator startAnimating]");
	
	[flickrPhoto loadLargeImageWithCompletion:^(FlickrPhoto *flickrPhoto, NSError *error) {
		[cell.activityIndicator stopAnimating];
		NSLog(@"[cell.activityIndicator stopAnimating]");
		
		if (error != nil) {
			return;
		}
		
		if (flickrPhoto.largeImage == nil) {
			return;
		}
		
		if (indexPath == self.largePhotoIndexPath) {
			FlickrPhotoCell *cell = (FlickrPhotoCell *)[collectionView cellForItemAtIndexPath:indexPath];
			if (cell != nil) {
				cell.imageView.image = flickrPhoto.largeImage;
			}
		}
	}];
	
	return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
//	if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
		FlickrPhotoHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FlickrPhotoHeaderView" forIndexPath:indexPath];
		headerView.backgroundColor = [UIColor yellowColor];
		headerView.label.text = self.searches[indexPath.section].searchTerm;
		return headerView;
//	}
//	NSAssert(false, @"Unexpected element kind");
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath 
{	
	if (self.sharing) {
		return YES;
	}
	
	if (self.largePhotoIndexPath == indexPath) {
		self.largePhotoIndexPath = nil;
	} else {
		self.largePhotoIndexPath = indexPath;
	}
	
	return NO;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//	UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
//	cell.selected = YES;
	NSLog(@"selectPhoto @ [index=%@]", indexPath);

	if (self.sharing) {
//		cell.backgroundColor = [UIColor greenColor];
		
		FlickrPhoto *photo = [self photoForIndexPath:indexPath];
		[self.selectedPhotos addObject:photo];
		[self updateSharedPhotoCount];
	}
}

//-(BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath
//{
//	NSLog(@"shouldDeselectPhoto @ [index=%@]", indexPath);
//	return YES;
//}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
//	UICollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
//	cell.selected = NO;
	NSLog(@"DeselectPhoto @ [index=%@]", indexPath);

	if (self.sharing) {		
//		cell.backgroundColor = [UIColor blackColor];

		NSUInteger foundIndex = [self.selectedPhotos indexOfObject:[self photoForIndexPath:indexPath]];
		if (foundIndex != NSNotFound) {
			[self.selectedPhotos removeObjectAtIndex:foundIndex];
			[self updateSharedPhotoCount];
		}
	}
}

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

#pragma mark - <UICollectionViewDelegateFlowLayout>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
	FlickrPhoto *flickrPhoto = [self photoForIndexPath:indexPath];
	
	if (indexPath == self.largePhotoIndexPath) {
		CGSize size = self.collectionView.bounds.size;
		NSLog(@"self.collectionView.bounds.size=[%f,%f]", size.width, size.height);
		UIEdgeInsets sectionInsets = {.top = 20.0, .left = 10.0, .bottom = 20.0, .right = 10.0};
		
		size.height -= [self.topLayoutGuide length];
		size.height -= (sectionInsets.top + sectionInsets.bottom);
		size.width -= (sectionInsets.left + sectionInsets.right);
		NSLog(@"size=[%f,%f]", size.width, size.height);

		
		return [flickrPhoto sizeToFillWidthOfSize:size];
	}
	
	CGSize size = flickrPhoto.thumbnail.size;
	if (size.width > 0) {
		size.width += 10;
		size.height += 10;
		return size;
	}
	return CGSizeMake(100, 100);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
	return UIEdgeInsetsMake(20.0, 10.0, 20.0, 10.0);
}

#pragma mark - <UITextFieldDelegate>

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	[textField addSubview:activityIndicator];
	[activityIndicator setFrame:textField.bounds];
	[activityIndicator startAnimating];
	
	[self.flickr searchFlickrForTerm:textField.text completion:^(FlickrSearchResults *results, NSError *error) {
				
		[activityIndicator removeFromSuperview];
		
		if (error != nil) {
			NSLog(@"Error searching : %@", error);
		}
		
		if (results != nil) {
			NSLog(@"Found %lu matching %@", (unsigned long)results.searchResults.count, results.searchTerm);
			[self.searches insertObject:results atIndex:0];
			
			[self.collectionView reloadData];
		}
		
	}];
	
	textField.text = nil;
	[textField resignFirstResponder];
	return YES;
}

@end
